#include "config.h"
#include "FileHelper.h"
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <WiFiManager.h>
#include "strings_cn.h"

#define parameters_size 65
#define MQTT_SECURE_DEFAULT false
#define MQTT_CERT_VALIDATE_DEFAULT false
#define MQTT_SECURE_SELF_SIGNED_INDEX_DEFAULT 0

static const char *PID_CONFIG_FILE = "/config.json";

FileHelper fileHelper(LittleFS);
// 是否保存配网参数
bool shouldSaveConfig = false;
// do we have been connected once to MQTT
char mqtt_user[parameters_size] = "mqtt_username"; // not compulsory only if your broker needs authentication
char mqtt_pass[parameters_size] = "mqtt_password"; // not compulsory only if your broker needs authentication
char mqtt_server[parameters_size];
char mqtt_port[6] = "1883";

PidConfig GlobalConfig;

PidConfig pid_config() {
    return GlobalConfig;
}

// 配网成功的回调
void saveConfigCallback()
{
    shouldSaveConfig = true;
}

// 重新初始化配网
void resetWifi()
{
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();

    esp_wifi_init(&cfg); // load resources and allocate memory
    delay(2000);
    if (esp_wifi_restore() != ESP_OK)
    {
        Serial.println("WiFi is not initialized by esp_wifi_init ");
    }
    else
    {
        Serial.println("WiFi Configurations Cleared!");
    }
    fileHelper.deleteFile(PID_CONFIG_FILE);
    delay(1000);
    ESP.restart();
}

bool pid_config_init()
{
    Serial.begin(115200);
    if (!LittleFS.begin(true))
    {
        Serial.println("LITTLEFS Mount Failed");
        return false;
    }
    WiFi.mode(WIFI_STA);
    // 读取配置文件
    size_t size = fileHelper.readFile(PID_CONFIG_FILE);
    if (size > 0)
    {
        JsonDocument json;
        deserializeJson(json, fileHelper.getFileContent());
        Serial.println("json file content");
        serializeJsonPretty(json, Serial);
        if (!json.isNull())
        {
            if (json.containsKey("mqtt_server"))
                strcpy(mqtt_server, json["mqtt_server"]);
            if (json.containsKey("mqtt_port"))
                strcpy(mqtt_port, json["mqtt_port"]);
            if (json.containsKey("mqtt_user"))
                strcpy(mqtt_user, json["mqtt_user"]);
            if (json.containsKey("mqtt_pass"))
                strcpy(mqtt_pass, json["mqtt_pass"]);
        }
    }

    WiFiManager wifiManager;
    WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, parameters_size, " minlength='1' maxlength='64' required");
    WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6, " minlength='1' maxlength='5' required");
    WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, parameters_size, " maxlength='64'");
    WiFiManagerParameter custom_mqtt_pass("pass", "mqtt pass", mqtt_pass, parameters_size, " input type='password' maxlength='64'");
    wifiManager.setSaveConfigCallback(saveConfigCallback);
    wifiManager.addParameter(&custom_mqtt_server);
    wifiManager.addParameter(&custom_mqtt_port);
    wifiManager.addParameter(&custom_mqtt_user);
    wifiManager.addParameter(&custom_mqtt_pass);
    if (!wifiManager.autoConnect("HidConfigWifi", ""))
    {
        resetWifi();
    }
    if (shouldSaveConfig)
    {
        strcpy(mqtt_server, custom_mqtt_server.getValue());
        strcpy(mqtt_port, custom_mqtt_port.getValue());
        strcpy(mqtt_user, custom_mqtt_user.getValue());
        strcpy(mqtt_pass, custom_mqtt_pass.getValue());

        JsonDocument json;
        json["mqtt_server"] = mqtt_server;
        json["mqtt_port"] = mqtt_port;
        json["mqtt_user"] = mqtt_user;
        json["mqtt_pass"] = mqtt_pass;
        fileHelper.writeFile(PID_CONFIG_FILE, json);
    }
    GlobalConfig.mqtt_server = mqtt_server;
    GlobalConfig.mqtt_port = std::stoi(mqtt_port);
    GlobalConfig.mqtt_user = mqtt_user;
    GlobalConfig.mqtt_pass = mqtt_pass;
    return true;
}

void pid_config_check()
{
    // boot按下 启动配网模式
    if (!digitalRead(BOOT_BTN))
    {
        resetWifi();
    }
    // Serial.printf("boot is:%d\n", digitalRead(BOOT_BTN));
    // Serial.printf("left is:%d\n", digitalRead(LED_LEFT));
    // Serial.printf("right is:%d\n", digitalRead(LED_RIGHT));
}
